<?php

namespace app\admin\controller\auth;

use ba\Auth;
use ba\Tree;
use Throwable;
use app\admin\model\AdminRule;
use app\common\controller\Backend;
use app\common\controller\PCBase;
use think\facade\Config;
class Rule extends PCBase
{
    protected string|array $preExcludeFields = ['create_time', 'update_time'];

    protected string|array $quickSearchField = 'title';

    /**
     * 权重字段
     * @var string
     */
    protected string $weighField = 'weigh';

    /**
     * 表格拖拽排序时,两个权重相等则自动重新整理
     * config/buildadmin.php文件中的auto_sort_eq_weight为默认值
     * null=取默认值,false=关,true=开
     * @var null|bool
     */
    protected null|bool $autoSortEqWeight = null;



    /**
     * @var object
     * @phpstan-var AdminRule
     */
    protected object $model;



    /**
     * @var Tree
     */
    protected Tree $tree;

    /**
     * 远程select初始化传值
     * @var array
     */
    protected array $initValue;

    protected string $dataLimitField = 'admin_id';

    /**
     * 搜索关键词
     * @var string
     */
    protected string $keyword;

    /**
     * 是否组装Tree
     * @var bool
     */
    protected bool $assembleTree;

    /**
     * 开启模型验证
     * @var bool
     */
    protected bool $modelValidate = false;

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new AdminRule();
        $this->tree  = Tree::instance();

        $isTree          = $this->request->param('isTree', true);
        $this->initValue = $this->request->get('initValue/a', []);
        $this->initValue = array_filter($this->initValue);
        $this->keyword   = $this->request->request('quickSearch', '');

        // 有初始化值时不组装树状（初始化出来的值更好看）
        $this->assembleTree = $isTree && !$this->initValue;
    }

    public function index()
    {

        if ($this->request->param('select')) {
            return $this->select();
        }

        return json(DefaultResponse(200, true, '获取成功', [
            'list'   => $this->getMenus(),
            'remark' => get_route_remark(),
        ]));
    }

    public function add()
    {
        $data = $this->request->post();
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }

        //去重复数据
        $title = $data['title']??'';
        if(!$title)  return json(DefaultResponse(201, false, '标题不能为空!', null));
//        $exist_info =  $this->model->where(['title'=>$title])->find();
//        if($exist_info)  return json(DefaultResponse(201, false, '标题已存在!', null));

        $data = $this->excludeFields($data);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $data[$this->dataLimitField] = $this->getAdminId();
        }
        $result = false;
        $this->model->startTrans();
        try {
            // 模型验证
            if ($this->modelValidate) {
                $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                if (class_exists($validate)) {
                    $validate = new $validate;
                    if ($this->modelSceneValidate) $validate->scene('add');
                    $validate->check($data);
                }
            }

            $result = $this->model->save($data);
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            return json(DefaultResponse(201, false, $e->getMessage(), null));
        }
        if ($result !== false) {
            return json(DefaultResponse(200, true, '添加成功', null));
        } else {
            return json(DefaultResponse(201, false, '添加失败', null));
        }
    }


    /**
     * 编辑
     * @throws Throwable
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            return json(DefaultResponse(201, false, '记录不能为空!', null));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            return json(DefaultResponse(201, false, '没有权限!', null));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                return json(DefaultResponse(201, false, '参数不能为空!', null));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                if (isset($data['pid']) && $data['pid'] > 0) {
                    // 满足意图并消除副作用
                    $parent = $this->model->where('id', $data['pid'])->find();
                    if ($parent['pid'] == $row['id']) {
                        $parent->pid = 0;
                        $parent->save();
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                return json(DefaultResponse(201, false, $e->getMessage(), null));
            }
            if ($result !== false) {
                return json(DefaultResponse(200, true, '操作成功', null));
            } else {
                return json(DefaultResponse(201, false, '更新失败', null));
            }
        }
        return json(DefaultResponse(200, true, '获取成功', ['row'=>$row]));
    }

    /**
     * 删除
     * @param array $ids
     * @throws Throwable
     */
    public function del(array $ids = [])
    {
        $data = $this->request->post();
        if (!$data||!$ids){
            return  json(DefaultResponse(201, false, '参数错误', null));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $pk      = $this->model->getPk();
        $data    = $this->model->where($pk, 'in', $ids)->select();
        $subData = $this->model->where('pid', 'in', $ids)->column('pid', 'id');
        foreach ($subData as $key => $subDatum) {
            if (!in_array($key, $ids)) {
                return  json(DefaultResponse(201, false, '请先删除子元素，或者使用批量删除', null));
            }
        }
        $count = 0;
        $this->model->startTrans();
        try {
            foreach ($data as $v) {
                $count += $v->delete();
            }
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            return  json(DefaultResponse(201, false, $e->getMessage(), null));
        }
        if ($count) {
            return  json(DefaultResponse(200, true, '操作成功!', null));
        } else {
            return  json(DefaultResponse(201, false, '未删除任何行!', null));
        }
    }

    /**
     * 重写select方法
     * @throws Throwable
     */
    public function select()
    {
        $data = $this->getMenus([['type', 'in', ['menu_dir', 'menu']], ['status', '=', '1']]);

        if ($this->assembleTree) {
            $data = $this->tree->assembleTree($this->tree->getTreeArray($data, 'title'));
        }
        return  json(DefaultResponse(200, true, '获取成功!', ['options'=>$data]));
    }

    /**
     * 获取菜单列表
     * @throws Throwable
     */
    protected function getMenus($where = []): array
    {
        $pk      = $this->model->getPk();
        $initKey = $this->request->get("initKey/s", $pk);

        $ids = (new Auth())->getRuleIds($this->getAdminId());

        // 如果没有 * 则只获取用户拥有的规则
        if (!in_array('*', $ids)) {
            $where[] = ['id', 'in', $ids];
        }

        if ($this->keyword) {
            $keyword = explode(' ', $this->keyword);
            foreach ($keyword as $item) {
                $where[] = [$this->quickSearchField, 'like', '%' . $item . '%'];
            }
        }

        if ($this->initValue) {
            $where[] = [$initKey, 'in', $this->initValue];
        }

        // 读取用户组所有权限规则
        $rules = $this->model
            ->where($where)
            ->order('weigh desc,id asc')
            ->select()->toArray();

        // 如果要求树状，此处先组装好 children
        return $this->assembleTree ? $this->tree->assembleChild($rules) : $rules;
    }


    /**
     * 排序
     * @param int $id       排序主键值
     * @param int $targetId 排序位置主键值
     * @throws Throwable
     */
    public function sortable(int $id, int $targetId)
    {
        $data = $this->request->post();

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $row    = $this->model->find($id);
        $target = $this->model->find($targetId);
        if (!$row || !$target) {
            return json(DefaultResponse(201, false, '记录不能为空!', null));
        }
        if ($row[$this->weighField] == $target[$this->weighField]) {
            $autoSortEqWeight = is_null($this->autoSortEqWeight) ? Config::get('buildadmin.auto_sort_eq_weight') : $this->autoSortEqWeight;
            if (!$autoSortEqWeight) {
                return json(DefaultResponse(201, false, '排序规则无效，因为两个目标的权重相等!', null));
            }

            // 自动重新整理排序
            $all = $this->model->select();
            foreach ($all as $item) {
                $item[$this->weighField] = $item[$this->model->getPk()];
                $item->save();
            }
            unset($all);
            // 重新获取
            $row    = $this->model->find($id);
            $target = $this->model->find($targetId);
        }

        $backup                    = $target[$this->weighField];
        $target[$this->weighField] = $row[$this->weighField];
        $row[$this->weighField]    = $backup;
        $row->save();
        $target->save();
        return  json(DefaultResponse(200, true, '操作成功!', null));
    }
}